package san.java.day14;

import java.lang.reflect.Method;

/**
 * 通过反射来调用指定方法
 */

public class Reflect_08 {

    public static void testMethod() throws Exception {
        Class<?> dogClass = Class.forName("san.java.day14.GoldenDog");

        GoldenDog dog = (GoldenDog) dogClass.getConstructor(String.class, int.class).newInstance("Big Yellow", 1);

        // 1. 调用公有方法
        Method setName = dogClass.getMethod("setName", String.class);
        setName.invoke(dog, "菠萝");

        System.out.println(dog.getName());

        // 2. 调用私有方法
        Method test = dogClass.getDeclaredMethod("test", String.class);

        // 解除私有方法的访问限制
        test.setAccessible(true);
        test.invoke(dog, "test");
    }

    public static void main(String[] args) {
        try {
            testMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
